<template>
  <div style="border: 1px solid #ccc">
    <toolbar
      style="border-bottom: 1px solid #ccc"
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
    />
    <editor
      style="height: 500px; overflow-y: hidden"
      v-model="valueHtml"
      :defaultConfig="editorConfig"
      @onCreated="handleCreated"
    />
    <cat-list v-model="selectValue" :empty="false"/>
    <p>{{selectValue}}</p>
  </div>
</template>

<script setup lang="ts">
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import CatList from "../public/cat-list";

import { onBeforeUnmount, ref, shallowRef, onMounted, reactive } from "vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { IEditorConfig, IToolbarConfig } from "@wangeditor/editor";
import setupUpload from "@/util/upload";

const editorConfig: Partial<IEditorConfig> = {
  placeholder: "请填写内容",
  MENU_CONF: {},
  hoverbarKeys: {
    attachment: {
      menuKeys: ["downloadAttachment"], // “下载附件”菜单
    },
  },
};

let selectValue = ref(2);

let formData = reactive({});

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();

// 内容 HTML
const valueHtml = ref("<p>hello</p>");

// 模拟 ajax 异步获取内容
// onMounted(() => {
//   setTimeout(() => {
//     valueHtml.value = "<p>模拟 Ajax 异步设置内容</p>";
//   }, 1500);
// });

let { progressNum,asyncRequest } = setupUpload(formData);

// 菜单栏配置，放在第22个位置
const toolbarConfig: Partial<IToolbarConfig> = {
  insertKeys: {
    index: 22, // 自定义插入的位置
    keys: ["uploadAttachment"], // “上传附件”菜单
  },
};

// 上传图片配置
editorConfig.MENU_CONF["uploadImage"] = {
  // 单个文件的最大体积限制，默认为 2M
  maxFileSize: 3 * 1024 * 1024, // 3M

  // 自定上传图片：上传到七牛云
  customUpload(file, insertFn) {
    asyncRequest({ file }).then((res) => {
      insertFn(res.file_path, res.file_name);
    });
  },
};

// 上传视频配置
editorConfig.MENU_CONF["uploadVideo"] = {
  // 单个文件的最大体积限制，默认为 10M
  maxFileSize: 20 * 1024 * 1024, // 20M

  // 自定上传视频：上传到七牛云
  customUpload(file, insertFn) {
    asyncRequest({ file }).then((res) => {
      insertFn(res.file_path);
    });
  },
};

// 上传附件配置
editorConfig.MENU_CONF["uploadAttachment"] = {
  maxFileSize: 10 * 1024 * 1024, // 10M

  // 自定上传附件：上传到七牛云
  customUpload(file, insertFn) {
    asyncRequest({ file }).then((res) => {
      console.log("res = ",res);
      insertFn(res.file_name, res.file_path);
    });
  },
};

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

const handleCreated = (editor) => {
  editorRef.value = editor; // 记录 editor 实例，重要！
  // 打印所有可配置的菜单项
  // console.log(editorRef.value.getAllMenuKeys());
};
</script>

<style scoped>
</style>